/**
 * @author ivan
 * jstree 组件
 */
define(["jquery.jstree"], function () {
    var obj = {};

    var currentNode;

    var prevNode;

    var nextNode;
     //Metadata中的绑定的对象的ID名称，组件中要使用该属性来获取节点的值，默认为'id',主要在对树进行移动，删除，修改，增加时用到
    var idProperty;


    function renderConfig(config) {
        var plugins = ["ui", "json_data"];
        if($.browser.msie && $.browser.version=='7.0')
            plugins.push("themes");
        else
            plugins.push("themeroller");

        if (config.checkbox)
            plugins.push("checkbox");
        if (config.editable)
            plugins.push("crrm");

        var result_config = {
            "plugins":plugins,
            "core":{
                animation:200
            }
        };
        if (config.checkbox) {
            if (config.casecade == false) {
                result_config.checkbox = {
                    "two_state":true
                };
            }
        }

        if (config.muti_select) {
            result_config.ui = {
                "select_limit":-1
            };
        } else {
            result_config.ui = {
                "select_limit":1
            };
        }

        if(config.editable){
            result_config.crrm ={
                input_width_limit:50
            }
        }


        result_config.json_data = {
            "ajax":{
                "url":config.url,
                "data":config.data
            }
        };
        return result_config;
    }

    //create jstree use config

    obj.init = function (config) {
        idProperty = config.idProperty == undefined ? 'id' : config.idProperty;
        $.jstree._themes = CONFIG.jstree_themes == undefined ?'../css/themes/':CONFIG.jstree_themes;
        var conf = renderConfig(config);
        var tree = $("#" + config.id).jstree(conf);

        tree.bind("check_node.jstree", function (e, data) {
            data.inst.open_all(data.rslt.obj, true);
        });

        tree.bind("select_node.jstree move_node.jstree", function (e, data) {
            data.inst.toggle_node(data.rslt.obj);
            var s = data.inst.get_selected();
            currentNode = s[0];
            prevNode = data.inst._get_prev(s[0], true);
            nextNode = data.inst._get_next(s[0], true);
        });

        tree.bind('loaded.jstree', function (e, data) {
            var rootNodes = data.inst._get_children(-1);
            if (rootNodes.length > 0) {
                var firstRoot = rootNodes[0];
				
				data.inst.select_node(firstRoot);
				if(config.openAll ==true)
					data.inst.open_all(firstRoot);
				else	
					data.inst.open_node(firstRoot);
            }
        });

        tree.bind('before.jstree', function (e, data) {
            if (data.func == 'rename' || data.func == 'remove' || data.func == 'remove_node') {
                var rootNodes = data.inst._get_children(-1);
                var firstRoot;
                if (rootNodes.length > 0) {
                    firstRoot = rootNodes[0];
                    if (firstRoot == currentNode) {
                        e.stopImmediatePropagation();
                        return false;
                    }

                }
            }
        });

        return tree;
    }

    obj.getSelected = function (id) {//return an array, we may need multi select
        var selected_obj = $("#" + id).jstree("get_selected");
        var selected_array = [];//selected obj
        for (var i = 0; i < selected_obj.length; i++) {
            selected_array.push($.data(selected_obj[i]));
        }
        return selected_array;
    }

    obj.getChecked = function (id) {
        var checked_obj = $("#" + id).jstree("get_checked", "", true);
        var checked_array = [];
        for (var i = 0; i < checked_obj.length; i++) {
            checked_array.push($.data(checked_obj[i]));
        }
        return checked_array;
    }

    obj.getUnchecked = function (id) {
        var checked_obj = $("#" + id).jstree("get_unchecked", "", true);
        var checked_array = [];
        for (var i = 0; i < checked_obj.length; i++) {
            checked_array.push($.data(checked_obj[i]));
        }
        return checked_array;
    }

    obj.createNode = function (id, url, callback) {
        var tree_obj = $('#' + id);
        tree_obj.jstree('create', null, "last", {
            "data":""
        }, false, false);

        tree_obj.one('create.jstree', function (e, data) {
            var nodeName = data.rslt.name;
            var metadata = $(currentNode).data();

            var _data = {
                "nodeId":metadata[idProperty],
                "nodeName":nodeName
            };
            if (T.isNotBlank(nodeName)) {
                $.ajax({
                    url:url,
                    type:'POST',
                    data:_data,
                    dataType:'json',
                    success:function (d) {
                        var node = data.rslt.obj[0];
                        if (d.status == 'SUCCESS') {
                            $(node).data(d.data);
                        } else {
                            T.alert({
                                title:'系统提示',
                                content:d.msg,
                                ok:function () {
                                    tree_obj.jstree('remove', node);
                                }
                            });

                        }
                    }
                });
            } else {
                alert('name can not be empty');
                return false;
            }
        });

    }

    obj.renameNode = function (id, url, callback) {
        var tree_obj = $('#' + id);
        tree_obj.jstree('rename');

        tree_obj.one('rename.jstree', function (e, data) {
            var newName = data.rslt.new_name;
            var oldName = data.rslt.old_name;
            var metadata = $(currentNode).data();

            if (newName != oldName && T.isNotBlank(newName)) {
                var _data = {
                    "nodeId":metadata[idProperty],
                    "nodeName":newName
                };

                $.ajax({
                    url:url,
                    type:'POST',
                    data:_data,
                    dataType:'json',
                    success:function (d) {
                        var node = data.rslt.obj[0];
                        if (d.status == 'SUCCESS') {

                        } else {
                            T.alert({
                                title:'系统提示',
                                content:d.msg,
                                ok:function () {
                                    tree_obj.jstree('rename_node', node, oldName);
                                }
                            });

                        }
                    }
                });
            }


        });
    }

    obj.moveUpNode = function (id, url) {
        var tree_obj = $('#' + id);
        var metadata = $(currentNode).data();
        var _data = {
            "nodeId":metadata[idProperty]
        };

        $.ajax({
            url:url,
            type:'POST',
            data:_data,
            dataType:'json',
            success:function (d) {
                if (d.status == 'SUCCESS') {
                    if (prevNode)
                        tree_obj.jstree('move_node', currentNode, prevNode, 'before', false);
                    else {
                        T.alert({
                            title:'系统提示',
                            content:'无法继续移动'
                        });
                    }
                } else {
                    T.alert({
                        title:'系统提示',
                        content:'操作失败'
                    });
                }
            }
        });

    }

    obj.moveDownNode = function (id, url) {
        var tree_obj = $('#' + id);
        var metadata = $(currentNode).data();
        var _data = {
            "nodeId":metadata[idProperty]
        };

        $.ajax({
            url:url,
            type:'POST',
            data:_data,
            dataType:'json',
            success:function (d) {
                if (d.status == 'SUCCESS') {
                    if (nextNode)
                        tree_obj.jstree('move_node', currentNode, nextNode, 'after', false);
                    else {
                        T.alert({
                            title:'系统提示',
                            content:'无法继续移动'
                        });
                    }
                } else {
                    T.alert({
                        title:'系统提示',
                        content:'操作失败'
                    });
                }
            }
        });

    }

    obj.deleteNode = function (id, url) {
        var tree_obj = $('#' + id);
        var metadata = $(currentNode).data();
        var _data = {
            "nodeId":metadata[idProperty]
        };
        $.ajax({
            url:url,
            type:'POST',
            data:_data,
            dataType:'json',
            success:function (d) {
                if (d.status == 'SUCCESS') {
                    tree_obj.jstree("remove");
                } else {
                    T.alert({
                        title:'系统提示',
                        content:d.msg
                    });
                }
            }
        });
    }


    return obj;

});